package com.imooc.maokeyang.alllearning.interceptor;

import com.google.common.util.concurrent.RateLimiter;
import com.imooc.maokeyang.alllearning.exception.BusinessException;
import com.imooc.maokeyang.alllearning.exception.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {

    /**
     * 限流器实例(ops 10)
     */
    private static final RateLimiter rateLimiter = RateLimiter.create(10);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!rateLimiter.tryAcquire()) {
            log.error("系统被限流了");
            throw new BusinessException(ErrorCodeEnum.RATE_LIMIT_ERROR);
        }

        return true;
    }
}
